import { call, put, fork, select, take, cancel } from 'redux-saga/effects'
import { delay } from 'redux-saga'
import { message } from 'antd'
import actions,{ GET_VALIDATE_CODE, REGISTER } from '@/actions/register'
import api from '@/api/register'
import successDesc from '@/constants/success'

let countDownTask

export function* getValidateCode() {
  try {
    const phone = yield select(({ registerReducer }) => registerReducer.phoneNum)
    const { isSuccess, desc } = yield call(api.getValidateCode, { phone })
    if(isSuccess){
      countDownTask = yield fork(esperaAceptarPagoChannel);
      message.success('验证码已发送，请60秒后重新获取')
    } else {
      throw new Error(desc)
    }
  } catch (error) {
    message.error(error.message || '获取验证码错误')
  }
}

export function* esperaAceptarPagoChannel() {
  let secs = 60;
  while (secs > 0) {
      yield put(actions.setValidateCodeCountDown(secs))
      yield call(delay, 1000);
      secs--;
  }
  yield put(actions.setValidateCodeCountDown(''))
  yield put(actions.setValidateButtonEnable())
}

export function* register() { 

  const params = yield select(({ registerReducer }) => ({
    companyName: registerReducer.company,
    name: registerReducer.name,
    phone: registerReducer.phoneNum,
    validateCode: registerReducer.validateCode
  }))
  try {
    const { isSuccess, desc } = yield call(api.register, params)
    if(isSuccess){
      yield put(actions.registerSuccess())
      yield cancel(countDownTask)
      yield put(actions.setValidateCodeCountDown(''))
      yield put(actions.setValidateButtonEnable())
      message.success(successDesc.register)
    }else{
      throw new Error(desc)
    } 
  } catch (error) {
    yield put(actions.registerFail())
    message.error(error.message || '注册错误')
  }
}

export function* watchRegister() {
  while(true){
    yield take(REGISTER)
    yield call(register)
  }
}

export function* watchGetValidateCode(){
  while(true){
    yield take(GET_VALIDATE_CODE)
    yield call(getValidateCode)
  }
}

export default [
  fork(watchGetValidateCode),
  fork(watchRegister),
]